package com.doit.day04

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import scala.io.Source

object _05_work {
  def main(args: Array[String]): Unit = {

    val conn: Connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test01", "root", "123456")

    val ps: PreparedStatement = conn.prepareStatement("insert into friends values (?,?)")
    val ps1: PreparedStatement = conn.prepareStatement("select friend from friends where cname=?")
    val ps2: PreparedStatement = conn.prepareStatement("update friends set friend = ? where cname = ?")

    //   (自己，我的朋友们)
    val list: List[(String, Array[String])] = Source.fromFile("data/sameFriends.txt")
      .getLines()
      .toList
      .map(line => (line.split(":")(0), line.split(":")(1).split(",")))

    //a 代表第一个朋友   b 代表第二个朋友
    list.reduce((a,b)=>{
      //a1 代表第一个朋友   b1 代表第二个朋友
      list.fold(a)((a1,b1)=>{
//A 的朋友们的集合
        a1._2.map((friend)=>{
//B    b1._2.contains(friend) 是否有A的朋友
          if (b1._2.contains(friend)){
            //todo   可以优化
            ps1.setString(1,a1._1+"与"+b1._1)
            val resultSet: ResultSet = ps1.executeQuery()
            //判断 可能空指针
            if (!resultSet.next()){
              //添加数据
              ps.setString(1,a1._1+"与"+b1._1)
              ps.setString(2,friend)
              ps.execute()
            }else{
              //追加数据
              val str: String = resultSet.getString(1)
              ps2.setString(1,str+friend)
              ps2.setString(2,a1._1+"与"+b1._1)
              ps2.execute()
            }
          }
          friend
        })
        a1
      })
      b
    })
  }
}
